//
//  SY_ManagerFormViewController.m
//  FaceRecognition
//
//  Created by syun on 2017/10/26.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_ManagerFormViewController.h"
#import "DropTable.h"
#import "SY_StuFormCustomCell.h"
#import "DateView.h"
#import "PNChart.h"
#import "SY_FormModel.h"
@interface SY_ManagerFormViewController ()<UITableViewDelegate,UITableViewDataSource,DropTableDelgate>

{
    DropTable * drop_table;
    NSString * currentMonth;
    NSString * count2;
    NSString * count0;
    NSString * count1;
    NSString * count3;
    NSInteger pageNum;
}
@property (nonatomic ,strong) UITableView *table;
@property (nonatomic ,strong) UIButton *monthButton;
@property (nonatomic ,strong) NSMutableArray *monthArray;
@property (nonatomic ,strong) NSMutableArray *countArray;
@property (nonatomic ,strong) PNPieChart *chartView;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic ,strong) UILabel * emptyLabel;
@end

@implementation SY_ManagerFormViewController

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}


- (NSMutableArray *)monthArray
{
    if (_monthArray == nil) {
        
        _monthArray = [NSMutableArray array];
    }
    
    return _monthArray;
}

- (NSMutableArray *)countArray
{
    if(_countArray == nil)
    {
        _countArray = [NSMutableArray array];
    }
    
    return _countArray;
}

- (UITableView *)table
{
    if (_table == nil) {
        
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, SCREENHEIGH - 64) style:UITableViewStylePlain];
        _table.dataSource = self;
        _table.delegate = self;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [self requestMoreStudentArrList];
            
        }];
        
        _emptyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 284 +(SCREENHEIGH - 348)/2, VIEW_WIDTH, 15)];
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.text = @"暂无数据";
        _emptyLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        _emptyLabel.textAlignment = NSTextAlignmentCenter;
        _emptyLabel.hidden = YES;
        [_table addSubview:_emptyLabel];
        
    }
    
    return _table;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.navigationItem.title = @"个人统计";
    pageNum = 1;
    currentMonth = [self getCurrentTime];
    [self downMonth];
    [self requestStudentMonthData];
    [self requestAllStudentArrList];
    [self.view addSubview:self.table];
    // Do any additional setup after loading the view.
}
#pragma tableDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 10)];
    view.backgroundColor = [UIColor colorWithHexString:@"f4f5f7"];
    return view;
  
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            return 40;
        }else
        {
            return 184;
        }
    }else
    {
        if (indexPath.row == 0) {
            
            return 40;
        }else
        {
            return 39;
        }
        
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 2;
    }else
    {
        return self.dataArray.count +1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
              UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
                if (cell == nil) {
                    
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    
                    UILabel *StuLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 150, 15)];
                    StuLabel.font = [UIFont boldSystemFontOfSize:16];
                    StuLabel.textColor = [UIColor colorWithHexString:@"000000"];
                    StuLabel.text = @"个人出勤";
                    [cell.contentView addSubview:StuLabel];
                    
                    _monthButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    _monthButton.frame = CGRectMake(SCREENWIDTH-12-115, 0, 115, 44);
                    [_monthButton setImageEdgeInsets:UIEdgeInsetsMake(0, 103, 0, 0)];
                    [_monthButton setTitleColor:[UIColor colorWithHexString:@"979797"] forState:UIControlStateNormal];
                    [_monthButton setTitle:currentMonth forState:UIControlStateNormal];
                    [_monthButton setImage:[UIImage imageNamed:@"record_head_classchoose_down_"] forState:UIControlStateNormal];
                    [_monthButton addTarget:self action:@selector(changeMonthAction:) forControlEvents:UIControlEventTouchUpInside];
                    [cell.contentView addSubview:_monthButton];
                    
                    UIView * line = [[UIView alloc]initWithFrame:CGRectMake(12, 39.5, SCREENWIDTH-12, 0.5)];
                    line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
                    [cell.contentView addSubview:line];
                }

                return cell;
            }else
            {
                UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"cell2"];
                if (cell == nil) {
                    
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
                    
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    
                }
                
                for (UIView *view in cell.contentView.subviews) {
                    
                    
                    [view removeFromSuperview];
                    
                }
                
                NSMutableArray *arrM = [NSMutableArray array];
                
                NSArray * colorArr = @[@"e8b8f9",@"b786ca",@"ffb7cf",@"ffd6b3"];
                
                 NSArray * numArr = @[count2,count0,count3,count1];
                
                NSString * txt2 = [NSString stringWithFormat:@"迟到 %@",count2];
                NSString * txt0 = [NSString stringWithFormat:@"旷课 %@",count0];
                NSString * txt3 = [NSString stringWithFormat:@"请假 %@",count3];
                NSString * txt1 = [NSString stringWithFormat:@"正常 %@",count1];
                
                NSArray * txtArr = @[txt2,txt0,txt3,txt1];
                
                NSLog(@"%@  %@  %@ ",numArr,colorArr,txtArr);
                
                for (int i = 0; i<4; i++) {
                    
                    NSString * colorStr = [NSString stringWithFormat:@"%@",[colorArr objectAtIndex:i]];
                    
                    PNPieChartDataItem *item =  [PNPieChartDataItem dataItemWithValue:[[numArr objectAtIndex:i] integerValue] color:[UIColor colorWithHexString:colorStr] description:[txtArr objectAtIndex:i]];
                    
                    [arrM addObject:item];
                }
                
                NSLog(@"%@",arrM);
                
                _chartView = [[PNPieChart alloc] initWithFrame:CGRectMake(30, 15, 140, 140) items:arrM];
                _chartView.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:11.0];
                _chartView.descriptionTextShadowColor = [UIColor clearColor];
                _chartView.showAbsoluteValues = NO;
                _chartView.showOnlyValues = NO;
                
                [_chartView strokeChart];
                
                
                _chartView.legendStyle = PNLegendItemStyleStacked;
                _chartView.legendFont = [UIFont systemFontOfSize:15];
                
                UIView *legend = [_chartView getLegendWithMaxWidth:200];
                [legend setFrame:CGRectMake(230, 64, legend.frame.size.width, legend.frame.size.height)];
                [cell.contentView addSubview:legend];
                
                [cell.contentView addSubview:_chartView];
                return cell;
            }
        
    }else
    {
            
           if (indexPath.row == 0) {
                 
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
                if (cell == nil) {
                    
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell3"];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
            
                UILabel *absenceLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 150, 15)];
                absenceLabel.font = [UIFont systemFontOfSize:16];
                absenceLabel.textColor = [UIColor colorWithHexString:@"000000"];
                absenceLabel.text = @"缺勤统计";
                [cell.contentView addSubview:absenceLabel];
            
                return cell;

        }else{
            
            SY_StuFormCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SY_StuFormCustomCell"];
            if (cell == nil) {
                
                cell = [[SY_StuFormCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SY_StuFormCustomCell"];
            }
            
            cell.timeLabel.text = @"2017.10.13";
            
            return cell;
        }
        
    }
    
}

   
- (void)changeMonthAction:(UIButton *)sender{
    
    drop_table = [[DropTable alloc] initWithView:sender];
    drop_table.lists = self.monthArray;
    drop_table.localtion = localtionTypeCustomRight;
    drop_table.delegate = self;
    drop_table.tableWidth = 120;
    drop_table.maginRight = 10;
}
#pragma mark -DropTableDelegate
//切换月份
- (void)tableViewCellSelected:(NSInteger)index{
    
    currentMonth = [self.monthArray objectAtIndex:index];
    [_monthButton setTitle:currentMonth forState:UIControlStateNormal];
    [self requestStudentMonthData];

}
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

-(void)downMonth
{
    RequestParam *param = [[RequestParam alloc] init];
    param.method = @"sy_rollcall_getmonth";
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = (NSDictionary *)jsonObject;
        NSArray * array = [dict objectForKey:@"re_data"];
        if (array.count > 0) {
            
            for (int i = 0 ; i< array.count; i++) {
                
                [self.monthArray addObject:[[array objectAtIndex:i] objectForKey:@"month"]];
                
            }
            
        }
        NSLog(@"%@",dict);
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:error.localizedDescription];
    }];
    
}
- (void)requestStudentMonthData
{
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    
    NSString * scid = [SYAccountTool ShareAccount].account.scid;
    [requestDic setObject:scid forKey:@"scid"];
    [requestDic setObject:currentMonth forKey:@"date"];
    [requestDic setObject:USERID forKey:@"userid"];
    [Utils Java_get:@"api/getStudentMonthTotle" parameters:requestDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if (arr.count > 3) {
                
            count2 = [[arr objectAtIndex:2]objectForKey:@"count"];
            count0=  [[arr objectAtIndex:0]objectForKey:@"count"];
            count1=  [[arr objectAtIndex:1]objectForKey:@"count"];
            count3=  [[arr objectAtIndex:3]objectForKey:@"count"];
            }
        
        [self.table reloadData];
        
    }failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)requestAllStudentArrList
{
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    
    NSString * scid = [SYAccountTool ShareAccount].account.scid;
    [requestDic setObject:scid forKey:@"scid"];
    [requestDic setObject:USERID forKey:@"userid"];
    [requestDic setObject:@"1" forKey:@"pageno"];
    [requestDic setObject:@"10" forKey:@"pagesize"];
    [Utils Java_get:@"api/getStudentArrList" parameters:requestDic success:^(NSInteger recode, id jsonObject) {
        
        [self.dataArray removeAllObjects];
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        NSLog(@"arr = %@",arr);
        if ([arr isKindOfClass:[NSNull class]] || ![arr isKindOfClass:[NSArray class]] || arr.count == 0) {
            
            [_emptyLabel setHidden:NO];
            [self.table.mj_footer endRefreshing];
            [self.table reloadData];
            return;
            
        }else
        {
            [_emptyLabel setHidden:YES];
            if (arr.count > 10) {
                
                for ( NSDictionary * dic in arr) {
                    
                    SY_FormModel * model = [SY_FormModel mj_objectWithKeyValues:dic];
                    [self.dataArray addObject:model];
                }
                
                
            }else
            {
                for ( NSDictionary * dic in arr) {
                    
                    SY_FormModel * model = [SY_FormModel mj_objectWithKeyValues:dic];
                    [self.dataArray addObject:model];
                }
                
            }
            pageNum =2;
            
        }
        
        [self.table reloadData];
        
    }failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:@"网络异常，请稍后重试！"];
    }];
}

- (void)requestMoreStudentArrList
{
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    
    NSString * scid = [SYAccountTool ShareAccount].account.scid;
    [requestDic setObject:scid forKey:@"scid"];
    [requestDic setObject:USERID forKey:@"userid"];
    [requestDic setObject:[NSString stringWithFormat:@"%ld",(long)pageNum] forKey:@"pageno"];
    [requestDic setObject:@"10" forKey:@"pagesize"];
    [Utils Java_get:@"api/getStudentArrList" parameters:requestDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        if ([arr isKindOfClass:[NSNull class]] || ![arr isKindOfClass:[NSArray class]] || arr.count == 0) {
            
            [self.table.mj_footer endRefreshing];
            [self.table reloadData];
            return;
        }else if (arr.count == 10)
        {
            for ( NSDictionary * dic in arr) {
                
                SY_FormModel * model = [SY_FormModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
            
            pageNum ++;
        }else
        {
            for ( NSDictionary * dic in arr) {
                
                SY_FormModel * model = [SY_FormModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
        }
        [self.table.mj_footer endRefreshingWithNoMoreData];
        [self.table reloadData];
        
    }failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:@"网络异常，请稍后重试！"];
        
        [self.table.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
